<?php

namespace App\Controllers\Image;
use App\Models\Image\Image;
class Upload extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = false;
    }
    public function execute() {
		$type = $this->request->get("type");//1：推广上传 2：头像上传 
		switch( $type ){
			case 1:
				$fileMulu = 'expand/';
				break;
			case 2:
				$fileMulu = 'avatar/';
				break;
			default:
				$fileMulu = '';
				break;
		}
		// Check if the user has uploaded files
		$data = array();
        if ($this->request->hasFiles()) {
			$filepath = '';
            $sid = date("YmdHis").mt_rand(1000, 9999);
            $types = ['png','jpg','jpeg','JPEG','JPG','PNG'];
            $files = $this->request->getUploadedFiles();
            // Print the real file names and sizes
            foreach ($files as $k=>$file) {
				if(empty( $file->getName() ) ){
					continue;
				}
                if(!in_array($file->getExtension(),$types)){
                    return \App\Libs\Views\Json::view(1, '上传类型错误', NULL); 
                }
				$filename = $sid . $k . '.' . $file->getExtension();
                $filepath = '/uploads/'.$fileMulu . $filename;
                $file->moveTo(APP_PATH.'/public/'.$filepath);
				
				$data[$k]['uri'] = DOMAIN_DOMAIN.$filepath;
                $data[$k]['name'] = $file->getName();
            }
        }
		return \App\Libs\Views\Json::view(0, 'ok', $data);
    }
}

